package com.example.bbgds.test.home.view;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.RelativeLayout;

import com.example.bbgds.test.R;
import com.example.bbgds.test.home.widget.AppItemInfo;
import com.example.bbgds.test.home.widget.WidgetDataMapping;
import com.example.bbgds.test.home.widget.ItemInfo;
import com.example.bbgds.test.home.widget.WidgetListAdapter;

/**
 * Created by zjzhu on 2016/4/26.
 */
public class HomeView extends RelativeLayout implements WidgetListAdapter.OnItemClickListener {

    private static final String TAG = "home";

    private RecyclerView mAppListView;
    private WidgetListAdapter mAdapter;

    public HomeView(Context context) {
        super(context);
    }

    public HomeView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public HomeView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onFinishInflate() {
        super.onFinishInflate();
        mAppListView = (RecyclerView) findViewById(R.id.applist);
        mAppListView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        mAppListView.setAdapter(mAdapter = new WidgetListAdapter(getContext()));
        mAdapter.setAppList(WidgetDataMapping.getAllWidgetList(getContext()));
        mAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(ItemInfo info, int position) {
        if (info instanceof AppItemInfo) {
            AppItemInfo aInfo = (AppItemInfo) info;
            startActivitySafely(aInfo.getLaunchIntent());
        }
    }

    private void startActivitySafely(Intent intent) {
        try {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            getContext().startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "Unable to launch. intent=" + intent, e);
        }
    }
}
